package com.vvlive.caibao.smartcity.utils;

import android.os.AsyncTask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhj on 2015/12/4.
 * 异步http请求
 */
public class AsyncHttpRequest extends AsyncTask<Object, Void, byte[]> {

    public static final String GET = "GET";
    public static final String POST = "POST";

    public interface CallBack {
        void onSuccess(byte[] data);

        void onFailure(int errCode, String msg);
    }

    private String mMethod = GET;
    private HashMap<String, String> mParams;
    private CallBack mCallBack;

    private AsyncHttpRequest() {
    }

    public static AsyncHttpRequest getRequester() {
        return new AsyncHttpRequest();
    }

    public AsyncHttpRequest setMethod(String method) {
        mMethod = method;
        return this;
    }

    public AsyncHttpRequest setParams(HashMap<String, String> params) {
        mParams = params;
        return this;
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected byte[] doInBackground(Object... params) {
        String url = params[0].toString();
        mCallBack = (CallBack) params[1];
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(params[0].toString()).openConnection();
            connection.setRequestMethod(mMethod);
            if (POST.equals(mMethod)) {
                connection.setDoInput(true);
                connection.setDoOutput(true);
                if (mParams != null) {
                    byte[] data = getParamsString(mParams).getBytes();
                    connection.getOutputStream().write(data, 0, data.length);
                }
            }
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return toByteArray(connection.getInputStream());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        if (mCallBack != null) {
            if (bytes != null) {
                mCallBack.onSuccess(bytes);
            } else {
                mCallBack.onFailure(1010, "HttpError");
            }
        }
    }

    /**
     * 读取输入流中的数据到byte数组
     *
     * @param stream
     * @return
     * @throws IOException
     */
    private static byte[] toByteArray(InputStream stream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = stream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        stream.close();
        return outputStream.toByteArray();
    }

    /**
     * 获取post请求的参数字符串
     *
     * @param params
     * @return
     */
    private static String getParamsString(HashMap<String, String> params) {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.append(entry.getKey());
            builder.append("=");
            builder.append(entry.getValue());
            builder.append("&");
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }
}
